import datetime
import random
import subprocess
import time
import threading


def adb_command(command, device_id=None):
    """调用 ADB 命令并返回输出。

    Args:
        command (list): ADB 命令及其参数的列表。
        device_id (str, optional): 如果指定，将针对该设备 ID 执行命令。

    Returns:
        tuple: 标准输出和标准错误。
    """
    adb_path = r"D:\soft\platform-tools\adb.exe"  # 指定 ADB 的完整路径
    full_command = [adb_path] + (['-s', device_id] if device_id else []) + command
    result = subprocess.run(full_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
    return result.stdout, result.stderr


def get_screen_resolution(device_id=None):
    """获取设备屏幕分辨率。

    Args:
        device_id (str, optional): 如果指定，将针对该设备 ID 获取分辨率。

    Returns:
        tuple: 屏幕宽度和高度。
    """
    stdout, stderr = adb_command(['shell', 'wm', 'size'], device_id)

    if stderr:
        raise Exception(f"Error retrieving screen size: {stderr.strip()}")

    resolution = stdout.strip().split(':')[-1].strip()
    width, height = map(int, resolution.split('x'))
    return width, height

# 返回上一页
def back(device_id=None):
    stdout, stderr = adb_command(['shell', 'input', 'keyevent', '4'], device_id)

    if stderr:
        raise Exception(f"Error executing back: {stderr.strip()}")
    else:
        print(f"Back command executed successfully on device: {device_id}, ['shell', 'input', 'keyevent', '4'], stdout: {stdout.strip()}, {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

def swipe(direction, device_id=None, num=0):
    """在设备上执行指定方向的滑动。

    Args:
        direction (str): 滑动方向，可以是 'up', 'down', 'left', 'right'。
        device_id (str, optional): 如果指定，将针对该设备 ID 执行滑动命令。
        num (int, optional): 滑动次数。
    """
    directions = {
        'up': (3 / 4, 1 / 4),
        'down': (1 / 4, 3 / 4),
        'left': (1 / 4, 3 / 4),
        'right': (3 / 4, 1 / 4),
    }

    if direction not in directions:
        raise ValueError(f"Invalid direction: {direction}. Valid directions are 'up', 'down', 'left', 'right'.")

    width, height = get_screen_resolution(device_id)

    # 计算滑动的起点和终点坐标
    x1, y1 = width // 2, int(height * directions[direction][0])
    x2, y2 = width // 2, int(height * directions[direction][1])

    if direction in ['left', 'right']:
        x1, x2 = int(width * directions[direction][0]), int(width * directions[direction][1])
        y1, y2 = height // 2, height // 2

    # 执行滑动命令
    stdout, stderr = adb_command(['shell', 'input', 'swipe', str(x1), str(y1), str(x2), str(y2)], device_id)

    if stderr:
        raise Exception(f"Error executing swipe: {stderr.strip()}")
    else:
        print(
            f"{direction.capitalize()} swipe command executed successfully on device: {device_id}, num: {num}, ['shell', 'input', 'swipe', {str(x1)}, {str(y1)}, {str(x2)}, {str(y2)}], stdout: {stdout.strip()}, {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")


def swipe_up(device_id=None, num=0):
    swipe('up', device_id, num)


def swipe_down(device_id=None, num=0):
    swipe('down', device_id, num)


def swipe_left(device_id=None, num=0):
    swipe('left', device_id, num)


def swipe_right(device_id=None, num=0):
    swipe('right', device_id, num)


def swipe_right_back(device_id=None, num=0):
    # 向左滑动
    swipe_right(device_id, num)

    sleep_time = random.randint(3, 5)
    time.sleep(sleep_time)

    # 返回上一页
    back(device_id)





def process_device(device_id, num, sleep_time):
    """处理单个设备的滑动操作。

    Args:
        device_id (str): 设备 ID。
        num (int): 滑动次数。
        sleep_time (int): 每次滑动后的休眠时间。
    """
    try:
        i = 0
        while i <= num:
            # 随机左滑然后返回
            true_probability = 20  # 20% 的概率选择 True
            false_probability = 100 - true_probability  # 80% 的概率选择 False
            if random.choices([True, False], weights=[true_probability, false_probability], k=1)[0]:
                swipe_right_back(device_id, i)
                time.sleep(random.randint(3, 5))
            swipe_up(device_id, i)
            time.sleep(sleep_time)
            i += 1
    except Exception as e:
        print(f"An error occurred on device {device_id}: {e}")
    print(f"Done on device {device_id}, {num} swipes, {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")


def get_connected_devices():
    """获取当前连接的所有设备。

    Returns:
        list: 设备 ID 列表。
    """
    stdout, stderr = adb_command(['devices'])
    if stderr:
        raise Exception(f"Error retrieving connected devices: {stderr.strip()}")

    devices = []
    for line in stdout.strip().split('\n')[1:]:
        if line.strip():
            device_id = line.split('\t')[0]
            devices.append(device_id)
    return devices


def main():
    # 获取所有连接的设备
    devices = get_connected_devices()

    if not devices:
        print("No devices connected.")
        return

    # 跑多少次
    num = 1000
    # 支付宝视频推荐
    sleep_time = random.randint(6, 12)  # 每次滑动后的休眠时间
    # 支付宝短剧
    # sleep_time = random.randint(16, 22)
    if sleep_time >= 16:
        # 支付宝短剧
        num = 50

    # 创建并启动线程处理每个设备
    threads = []
    for device_id in devices:
        thread = threading.Thread(target=process_device, args=(device_id, num, sleep_time))
        threads.append(thread)
        thread.start()

    # 等待所有线程完成
    for thread in threads:
        thread.join()

    print("All devices processed.")


if __name__ == "__main__":
    main()